﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace TaskLauncher.View.Converters
{
    class ParameterConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string toString = "";
            foreach (var par in value as string[])
            {
                string safePar = par.Replace("\"", "\\\"");
                safePar = (safePar.Contains(' ') ? '"' + safePar + '"' : safePar);
                if (toString.Length == 0)
                    toString = safePar;
                else
                    toString += " " + safePar;
            }
            return toString;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            List<string> parameters = new List<string>();
            string currentParameter = "";
            bool insideDoubleQuotes = false;
            bool lastWasEscapeBackSlash = false;

            for(int i = 0; i < (value as string).Length; i++)
            {
                switch((value as string)[i])
                {
                    case '\\':
                        if (insideDoubleQuotes || lastWasEscapeBackSlash)
                            currentParameter += '\\';
                        lastWasEscapeBackSlash = !insideDoubleQuotes;
                        break;

                    case '"':
                        if (lastWasEscapeBackSlash)
                            currentParameter += '"';
                        else
                            insideDoubleQuotes = !insideDoubleQuotes;
                        lastWasEscapeBackSlash = false;
                        break;

                    case ' ':
                        if (insideDoubleQuotes || lastWasEscapeBackSlash)
                            currentParameter += ' ';
                        else if(currentParameter.Length != 0)
                        {
                            parameters.Add(currentParameter);
                            currentParameter = "";
                        }
                        lastWasEscapeBackSlash = false;
                        break;

                    default:
                        if (lastWasEscapeBackSlash)
                            currentParameter += '\\';
                        currentParameter += (value as string)[i];
                        lastWasEscapeBackSlash = false;
                        break;
                }
            }

            if (lastWasEscapeBackSlash)
                currentParameter += '\\';
            if (currentParameter.Length != 0)
                parameters.Add(currentParameter);

            return parameters.ToArray();
        }
    }
}
